<?php

declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Db;

class NotifyMessage extends Model
{
    protected $name = 'notify_message';

    protected $autoWriteTimestamp = 'datetime';

    protected $append = ['status_label'];

    protected $type = [
        'payload' => 'array',
        'sent_at' => 'datetime',
    ];

    public const STATUS_PENDING = 0;
    public const STATUS_SENT = 1;

    private static ?bool $supportsSentAtCache = null;

    public static function statusMap(): array
    {
        return [
            self::STATUS_PENDING => '待发送',
            self::STATUS_SENT => '已发送',
        ];
    }

    public static function supportsSentAt(): bool
    {
        if (self::$supportsSentAtCache !== null) {
            return self::$supportsSentAtCache;
        }

        try {
            $table = (new static())->getTable();
            $result = Db::query(sprintf('SHOW COLUMNS FROM `%s` LIKE "sent_at"', $table));
            self::$supportsSentAtCache = $result !== [];
        } catch (\Throwable $e) {
            self::$supportsSentAtCache = false;
        }

        return self::$supportsSentAtCache;
    }

    public function recipients()
    {
        return $this->hasMany(NotifyRecipient::class, 'message_id', 'id');
    }

    public function template()
    {
        return $this->belongsTo(NotifyTemplate::class, 'template_id', 'id');
    }

    public function getStatusLabelAttr(): string
    {
        return self::statusMap()[(int) $this->status] ?? '未知';
    }
}
